package com.aopeng.controller;

import com.aopeng.entity.AopengExamination;
import com.aopeng.inter.WebServiceInter;
import com.aopeng.inter.impl.WebServiceInterImpl;
import com.aopeng.mapper.AopengExaminationMapper;
import com.aopeng.service.impl.WordExcelToHtml;
import java.io.File;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.unbescape.html.HtmlEscape;

/**
 * zqh
 * 对试卷操作
 */
@Controller
public class AopengExaminationController {
    @Autowired
    private AopengExaminationMapper aopengExaminationMapper;
    @Autowired
    private WebServiceInter webServiceInter;
    @Autowired
    private WordExcelToHtml wordExcelToHtml;
    public static int index = 0;
    //获取所有的数据
    @RequestMapping("/getAopengExamination")
    public  String getAopengExamination(AopengExamination aopengExamination,Model model){
        index = Math.toIntExact(aopengExamination.getId());
        System.out.println("查询全部"+index);
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("school_id",index);//写表中的列名
        List<AopengExamination> getAopengExamination = aopengExaminationMapper.selectByMap(columnMap);
        model.addAttribute("getAopengExamination",getAopengExamination);
        return "admin/AopengExamination";
    }

    //根据id获取数据
    @RequestMapping("/getAopengExaminationById")
    public void getAopengExaminationById(){
        System.out.println("根据id查询");
        //获取前台传过来的数据
        int index = 1;
        AopengExamination aopengExamination = aopengExaminationMapper.selectById(index);
        System.out.println(aopengExamination);
    }

    //根据id修改数据
    @RequestMapping("/updateAopengExaminationById")
    public void updateAopengExaminationById(){
        System.out.println("根据id修改数据");
        //获取前台传过来的数据
        int index = 1;
        AopengExamination aopengExamination = new AopengExamination();
        int i = aopengExaminationMapper.updateById(aopengExamination);
        System.out.println(i);
    }

    //跳转
    @RequestMapping("/tiaozhuan")
    public String tiaozhuan(){
        return "admin/insert-AopengExamination.html";
    }

    //增加数据
    @RequestMapping("/insertAopengExamination")
    public String insertAopengNaccolumn(MultipartFile[] file,AopengExamination aopengExamination)throws Exception{
        for (int i = 0; i < file.length; i++) {
            String filePath = file[i].getContentType().substring(0, file[i].getContentType().indexOf("/"));
            String substring = file[i].getOriginalFilename().substring(0, file[i].getOriginalFilename().length());
            String[] split = substring.split("/");//以逗号分割
            for (String string2 : split) {
                substring = string2;
            }
            if (filePath.equals("application")){
                String wordFileName = substring.substring(substring.indexOf(".") + 1, substring.length());
                InputStream inputStream = file[i].getInputStream();
                FileInputStream fis = (FileInputStream) inputStream;
                String description = "";
                String content = "";
                if (wordFileName.equals("doc")) {
                    content = wordExcelToHtml.getWordAndStyle((FileInputStream) file[i].getInputStream());
                    //获取文本内容截取前100个字符做文章描述
                    WordExtractor ex = new WordExtractor(fis);
                    description = ex.getText();
                } else if (wordFileName.equals("docx")) {
                    content = wordExcelToHtml
                        .getDocxWordToHtml((FileInputStream) file[i].getInputStream());
                    //获取文本内容截取前100个字符做文章描述
                    XWPFDocument xdoc = new XWPFDocument(fis);
                    XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
                    description = extractor.getText();
                }
                aopengExamination.setDescription(description.substring(description.length()>40?40:0, description.length()>250?250:description.length()));
                //StringEscapeUtils.unescapeHtml3进行编码格式转换
                aopengExamination.setExaminationContent(StringEscapeUtils.unescapeHtml3(content));
            } else if (filePath.equals("text")){
                InputStream inputStream = file[i].getInputStream();
                InputStreamReader w1 = new InputStreamReader(inputStream,"GBK");
                BufferedReader br = new BufferedReader(w1);
                String inString = null; //用来存放缓冲流内容的字符串
                String str = "";
                while ((inString = br.readLine()) != null) { //当inString不为空时，代表有数据可读
                    str += "\r";
                    str += inString;
                }
                aopengExamination.setExaminationContent(str);
            }else{
                System.out.println(substring+"文件格式错误！");
            }
            aopengExamination.setSchoolId((long) index);
            aopengExamination.setExaminationName(substring.substring(0,substring.indexOf(".")));

            aopengExaminationMapper.insert(aopengExamination);
        }
//        webServiceInter.submitBaiDu();
        return "redirect:/getAopengExamination?id="+index+"";
    }
    /*public String insertAopengNavcolumn(MultipartFile[] file,AopengExamination aopengExamination) throws Exception {
        for (int i = 0; i < file.length; i++) {
//            String s1 = new String(file[i].getOriginalFilename().getBytes("UTF-8"), "UTF-8");
            String indexof = file[i].getContentType().substring(0, file[i].getContentType().indexOf("/"));
            if (indexof.equals("text")){
                String substring = file[i].getOriginalFilename().substring(0, file[i].getOriginalFilename().length());
                String[] split = substring.split("/");//以逗号分割
                for (String string2 : split) {
                    substring = string2;
                }
                InputStream inputStream = file[i].getInputStream();
                InputStreamReader w1 = new InputStreamReader(inputStream,"GBK");
                BufferedReader br = new BufferedReader(w1);
                String inString = null; //用来存放缓冲流内容的字符串
                String str = "";
                while ((inString = br.readLine()) != null) { //当inString不为空时，代表有数据可读
                    str += "\r";
                    str += inString;
                }
                System.out.println("==============================="+indexof);
                aopengExamination.setExaminationContent(str);
                aopengExamination.setSchoolId((long) index);
                aopengExamination.setExaminationName(substring.substring(0,substring.indexOf(".")));
                aopengExaminationMapper.insert(aopengExamination);
                System.out.println("==============================="+aopengExamination);

                Map<String,Object> columnMap = new HashMap<>();
                columnMap.put("examination_name",substring.substring(0,substring.indexOf(".")));//写表中的列名
                List<AopengExamination> aopengExaminations = aopengExaminationMapper.selectByMap(columnMap);
            }else if (indexof.equals("application")){
                String substring = file[i].getOriginalFilename().substring(0, file[i].getOriginalFilename().length());
                String[] split = substring.split("/");//以逗号分割
                for (String string2 : split) {
                    substring = string2;
                }
                //文件名加后缀
                System.out.println("数据1-->>>" + substring);
                //文件名
                System.out.println("数据2-->>>" + substring.substring(0,substring.indexOf(".")));
                //后缀
                System.out.println("数据3-->>>" + substring.substring(substring.indexOf(".")+1,substring.length()));
                if(substring.substring(substring.indexOf(".")+1,substring.length()).equals("docx")){
                    //docx
                    String str = "";
                    InputStream inputStream = file[i].getInputStream();
                    FileInputStream fis = (FileInputStream) inputStream;
                    XWPFDocument xdoc = new XWPFDocument(fis);
                    XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
                    str = extractor.getText();
                    aopengExamination.setExaminationContent(str);
                }else {
                    //doc
                    String buffer="";
                    InputStream inputStream = file[i].getInputStream();
                    InputStream is = (FileInputStream) inputStream;
                    WordExtractor ex = new WordExtractor(is);
                    buffer = ex.getText();
                    aopengExamination.setExaminationContent(buffer);
                }
                aopengExamination.setSchoolId((long) index);
                aopengExamination.setExaminationName(substring.substring(0,substring.indexOf(".")));
                aopengExaminationMapper.insert(aopengExamination);

                Map<String,Object> columnMap = new HashMap<>();
                columnMap.put("examination_name",substring.substring(0,substring.indexOf(".")));//写表中的列名
                List<AopengExamination> aopengExaminations = aopengExaminationMapper.selectByMap(columnMap);
            }

        }
        webServiceInter.submitBaiDu();
//            System.out.println("++++++++++++++++++++"+file[i].getContentType());//在控制台打印文件的类型
//            System.out.println("++++++++++++++++++++"+file[i].getName());//返回文件的名称
//            System.out.println("++++++++++++++++++++"+file[i].getOriginalFilename());//返回文件的原文件名
        return "redirect:/getAopengExamination?id="+index+"";
    }*/

    //根据id删除
    @RequestMapping("/deleteAopengExaminationById")
    public String deleteAopengExaminationById(long id){
        System.out.println("根据id删除数据"+id);
        AopengExamination aopengExamination = aopengExaminationMapper.selectById(id);
        //需将所有相关图片也一起删除
        String content = aopengExamination.getExaminationContent();
        if (content==null)
            content="";
        List<String> regexString = wordExcelToHtml.getRegexString(content, "<img.*>|<img.*/>");
        if (regexString!=null&&regexString.size()>0){
            for (String str :
                regexString) {
                String replaceAll = wordExcelToHtml.getRegexString(str, "src=\"(\\S*?)[^\"]*\".*?").get(0);
                String imgName = replaceAll.substring(replaceAll.lastIndexOf("/")+1, replaceAll.length()-1);
                System.out.println(imgName);
                File file = new File("/usr/local/tomcat/image/"+imgName);
                System.out.println(file.isFile());
                System.out.println(file.getPath());
                if (!file.exists()) {
                    System.out.println("删除文件失败:" + imgName + "不存在！");
                } else {
                    if (file.exists() && file.isFile()) {
                        if (file.delete()) {
                            System.out.println("删除单个文件" + imgName + "成功！");
                        } else {
                            System.out.println("删除单个文件" + imgName + "失败！");
                        }
                    }
                }
            }
        }

        aopengExaminationMapper.deleteById(id);
        return "redirect:/getAopengExamination?id="+index;
    }
}
